<?php

namespace App\Http\Middleware;

use App\Facades\UserManager;
use Cache;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Request;
use Response;

class Offline
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = Cache::remember(session('openId'), env('CACHE_USER_TIME', 1), function(){
            return UserManager::getWxUser();
        });

        if(!(empty($user->current_device_code) || is_null($user->current_device_code))){
            if(Request::ajax() || Request::wantsJson()){
                $fd = Cache::get($user->current_device_code.'fd');
                $fds = Cache::get('fds');
                if(is_null($fd) || is_null($fds) || !in_array($fd, $fds)) {
                    Cache::forget($user->current_device_code.'state');
                    return Response::json(['status' => config('exceptions.device.notConnect')]);
                }
            }
        }
        return $next($request);
    }
}